package com.zl.cms.service;

import com.zl.basic.CommonUtil.Check;
import com.zl.basic.CommonUtil.SecurityUtil;
import com.zl.basic.model.Pager;
import com.zl.cms.dao.*;
import com.zl.cms.exception.CmsException;
import com.zl.cms.model.*;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.List;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-1-15 Time: 下午8:33
 */
@Service("userService")
public class UserService implements IUserService {

  private IUserDao userDao;
  private IRoleDao roleDao;
  private IGroupDao groupDao;

  public IUserDao getUserDao() {
    return userDao;
  }

  @Inject
  public void setUserDao(IUserDao userDao) {
    this.userDao = userDao;
  }

  public IRoleDao getRoleDao() {
    return roleDao;
  }

  @Inject
  public void setRoleDao(IRoleDao roleDao) {
    this.roleDao = roleDao;
  }

  public IGroupDao getGroupDao() {
    return groupDao;
  }

  @Inject
  public void setGroupDao(IGroupDao groupDao) {
    this.groupDao = groupDao;
  }

  @Override
  public void add(User user, Integer[] rids, Integer[] gids) {

    User tu = userDao.loadByUsername(user.getUsername());
    if (null != tu) {
      throw new CmsException("the user has existed,cant't add");
    }

    user.setPassword(SecurityUtil.md5(user.getUsername(),user.getPassword()));
    // userDao.checkObjectNull(user.getId());
    userDao.add(user);
    // 添加用户角色关系对象
    for (Integer rid : rids) {
      addUserRole(user, rid);

    }
    // 添加用户和组关系对象
    for (Integer gid : gids) {
      addUserGroup(user, gid);
    }
  }

  private void addUserGroup(User user, Integer gid) {
    // 1检查组对象是否存在,如果不存在就抛出异常
    Group g = groupDao.load(gid);
    Check.checkAnyNull(g, "added group not exist");
    // 2检查用户和组关系,如果存在就不添加
    UserGroup ug = userDao.loadUserGroup(user.getId(), gid);
    if (null != ug) return;
    userDao.addUserGroup(user, g);
  }

  private void addUserRole(User user, Integer rid) {
    // 1检查角色对象是否存在,如果不存在就抛出异常
    Role role = roleDao.load(rid);
    Check.checkAnyNull(role, "added role not exist");
    // 2检查用户和角色关系,如果存在就不添加
    UserRole ur = userDao.loadUserRole(user.getId(), rid);
    if (null != ur) return;
    userDao.addUserRole(user, role);
  }

  @Override
  public void delete(int id) {

    // TODO 需要进行用户是否有文章的判断

    // 1删除用户关联的角色对象
    userDao.deleteUserRole(id);
    // 2删除用户关联的组对象
    userDao.deleteUserGroup(id);
    // 3删除用户对象
    userDao.delete(id);
  }

  @Override
  public void update(User user, Integer[] rids, Integer[] gids) {
    // 检查用户是否存在
    userDao.checkObjectNull(user.getId());
    // 获取用户已经存在的组id和角色id
    List<Integer> erids = userDao.listUserRoleIds(user.getId());
    List<Integer> egids = userDao.listUserGroupsIds(user.getId());
    // TODO 以后可以考虑使用java.util.concurrent 包里的方法，边删除边添加
    // 添加，如果rids中的id不在erids中就要添加
    for (Integer rid : rids) {
      if (!erids.contains(rid)) {
        addUserRole(user, rid);
      }
    }
    for (Integer gid : gids) {
      if (!egids.contains(gid)) {
        addUserGroup(user, gid);
      }
    }

    // 删除,如果erids的id不在rids中就删除
    for (Integer erid : erids) {
      if (!ArrayUtils.contains(rids, erid)) {
        userDao.deleteUserRole(user.getId(), erid);
      }
    }
    // 删除,如果egids的id不在gids中就删除
    for (Integer egid : egids) {
      if (!ArrayUtils.contains(gids, egid)) {
        userDao.deleteUserGroup(user.getId(), egid);
      }
    }
  }

  @Override
  public void updateStatus(int id) {

    User u = userDao.load(id);
    Check.checkAnyNull(u, "updated user not exist,can not update");
    if (u.getStatus() == 0) {
      u.setStatus(1);
    } else {
      u.setStatus(0);
    }
    userDao.update(u);

  }

  @Override
  public Pager<User> findUser() {
    return userDao.findUser();
  }

  @Override
  public User load(int id) {
    return userDao.load(id);
  }

  @Override
  public List<Role> listUserRoles(int id) {
    return userDao.listUserRoles(id);
  }

  @Override
  public List<Group> listUserGroups(int id) {
    return userDao.listUserGroups(id);
  }

  @Override
  public List<Integer> listUserRoleids(int id) {
    return userDao.listUserRoleIds(id);
  }

  @Override
  public List<Integer> listUserGroupids(int id) {
    return userDao.listUserGroupsIds(id);
  }

  @Override
  public List<User> listGroupUsers(int gid) {
    return userDao.listUsersByGroupId(gid);
  }

  @Override
  public List<User> listRoleUsers(int rid) {
    return userDao.listUsersByRoleId(rid);
  }

  @Override
  public User login(String username, String passowrd) {
    User u = userDao.loadByUsername(username);
    Check.checkAnyNull(u, "用户名或者密码不正确");
    if (!SecurityUtil.md5(username,passowrd).equals(u.getPassword())) {
      throw new CmsException("用户名或者密码不正确");
    }
	  if(u.getStatus()==0) {
		  throw new CmsException("用户已经停用,不能登陆");
	  }
    return u;
  }

	@Override
	public void updatePwd(int uid, String oldPwd, String newPwd) {
		User u = userDao.load(uid);
		if(!SecurityUtil.md5(u.getUsername(),oldPwd).equals(u.getPassword())){
				throw  new  CmsException("原始密码不正确");
		}
		u.setPassword(SecurityUtil.md5(u.getUsername(),newPwd));
		userDao.update(u);
	}

	@Override
	public void update(User user) {
		userDao.update(user);
	}
}
